<?php

namespace Jtbk\Controller;
use Think\Page;
use Think\Controller;


/**
 * 集体备课控制器
 * @author水月居 <singliang@163.com>
 */
class ShitiController extends Controller {
	public function _initialize()
    {
       header("Content-type: text/html; charset=utf-8");
       $uid=is_login();
       if($uid){
        $my['teacher']=query_user('nickname');
        $my['uid']=$uid;
        $this->assign(my,$my);               
          }else{
          $this->error('请先登录',U('/Home/User/login'),3);
        }	
    }

    /**
     * 集体备课首页
    */
    public function index(){
    	$subjectModel=D('JxSubject');
    	$sublist=$subjectModel->order(array('sort'=>'asc'))
    	         ->where(array('shiti'=>1))->field('id,subject,logo')->select();
	    $shitimodel=D('JxShitiFile');
	    $order=array('subject'=>'desc','grade'=>'desc','update_time'=>'desc');
	    foreach($sublist as $key => $value){
	    	$value['postlist']=$shitimodel
	    	->field('id,title,teacher,grade,update_time')
	    	->limit(6)->order($order)
	    	->where(array('subject_id'=>$value['id']))->select();
	    	$data[]=$value;
	    	
	    }
	    //dump($beikepost->getLastSql());// dump($sublist);
	    //dump($data);

	    // $tlist=$beikepost->field("id,grade,subject,title")->order($order)->limit('0,6')->select();
	    $this->assign('list', $data);
        $this->display();
    }


    /*上传试题*/
    public function add(){
       $subjectModel=D('JxSubject');
       $sublist=$subjectModel->where(array('shiti'=>1))->field('id,subject')->select();
       //dump($sublist);
       $this->assign(sublist,$sublist);
		 if(IS_POST){
		 //post检测
            if(!$_POST['sid']){
                $this->error("请选择上传学科类别后再上传",Cookie('__forward__'),3);
                }
            if(!I('post.title')){
                $this->error("请检查试卷标题是否填写完整",Cookie('__forward__'),2);
                }                               
	       	if(!I('post.cate')){
	          $this->error("请先选择上传类别后再上传",Cookie('__forward__'),3);
	       	}

	       $sid=I('post.sid');
	       $info=$subjectModel->getSubjectInfo($sid);
	       $subject= $info['subject'];
	       $savepath=$info['savepath'];
	       $fileModel=D('JxShitiFile');
	       $savepath.='/';
	       $save= $postinfo['subject'].I('grade').I('title').I('post.teacher').date(ymd);
	       $config = array(
	            'maxSize'    =>   50*1024*1024, // 设置附件上传大小
	            'rootPath'   =>    './Uploads/Shiti/',
	            'savePath'   =>    $savepath,
	            'saveName'   =>    uniqid(),//iconv('utf-8', 'gbk', $save),
	            'exts'       =>    array('jpg', 'gif', 'png', 'zip', 'rar', 'doc', 'docx','pdf'),
	            'autoSub'    =>    true,
	            'subName'    =>    C('CUR_YEAR'),
             );

          $upload = new \Think\Upload($config);// 实例化上传类 
          $info   =  $upload->upload();
			$file_ext = pathinfo($_FILES['upfile']['name'], PATHINFO_EXTENSION );
			 // dump($info);
		  //    exit;
					// array(1) {
					//   ["upfile"] => array(9) {
					//     ["name"] => string(17) "565c3daab9a65.doc"
					//     ["type"] => string(18) "application/msword"
					//     ["size"] => int(458069)
					//     ["key"] => string(6) "upfile"
					//     ["ext"] => string(3) "doc"
					//     ["md5"] => string(32) "a20ec635b4c1df46d26aee9ca09fa742"
					//     ["sha1"] => string(40) "129b3ae241a4c464caf12205e24033dbb3c97af5"
					//     ["savename"] => string(17) "565c3daab9a65.doc"
					//     ["savepath"] => string(6) "yuwen/2015/"
					//   }
					// }
			if(!$info) {
				        // 上传错误提示错误信息
				        $this->error($upload->getError(),Cookie('__forward__'),3);
				       }else{
                    // 上传成功保存表单数据				       
				    $url= $info['upfile']['savepath'].$info['upfile']['savename'];    
				    $data=array(
				    	 'grade'      =>I('post.grade'),
				    	 'subject_id' => $sid,			             		             
				    	 'subject'    => $subject,
				    	 "teacher"    => I('teacher'),                         
				         "title"      => I('post.title'),
			             'keyword'    =>$subject.','.I('grade').','.I('title').','.I('teacher'),
				         'cate'       =>I('post.cate'),
				    	 "file_url"   => $url,                       
				         "file_name"  =>$_FILES['upfile']['name'],
                         'file_ext'   => $file_ext,
				         "title"      => I('post.title'),
                         "year"=>C('CUR_YEAR'),
				     );
				 $fileModel->create($data);
		         if($fileModel->add()){ 
		            $this->success('上传成功！');		         	
		         }else{
		         	$this->success('保存失败！');
		         }
		       }
		   }


       $this->display();
	}



/*编辑上传资料*/
  public function edit()
  {
  
  $id=I('get.id');
  $shitiModel=D('JxShitiFile');
  $postinfo=$shitiModel->field('s_key',true)->find($id);//排除指定项其他都选取
  //dump($postinfo);
  //dump($uid);
  if(!$postinfo){
    $this->error('参数错误');
  }else{
    $uid=is_login();
    if($uid!=$postinfo['uid']){
      $this->error('对不起，您不能修改别人上传的资料！');
    }
    $this->assign('info',$postinfo);
  }

    if(IS_POST){
      $shitiModel->create(I('post'));
      $shitiModel->save();
      $this->success('更新成功！');
    }
  $this->display();
  }

	/**@水月居
	*我的上传*
	**/
	public function myupload($uid=0)
	{
	  	$uid=is_login();
	  	$map['uid'] = $uid;
	    $list=D('JxShitiFile')->where($map)->select();
	    $this->assign('list',$list);
	  $this->display();
	 }
   /**@todo
	*显示文档详情*
	**/
  public function detail($id=0) {
    $post_id=I('get.id'); 
    $post=D('JxShitiFile')->find($post_id);
    $this->assign('alist',$post);
    $this->display();
  }
   /**@todo
  *下载附件*
  **/
   public function download(){
    $id=I('fid');
    $afile=D('JxShitiFile')->find($id);

    //判断文件是否存在
    $file_path = './Uploads/Shiti/'.$afile['file_url'];
    
    $file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码
    if (!file_exists($file_path)) {
      $this->error('文件不存在！');
    }
    $file_name =$afile['file_name']; //获取文件名称 basename()
    $file_size = filesize($file_path); //获取文件大小
    $fp = fopen($file_path, 'r'); //以只读的方式打开文件
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: {$file_size}");
                 if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
                 header('Content-Disposition: attachment; filename="' . rawurlencode($file_name) . '"');
             } else {
                 header('Content-Disposition: attachment; filename="' . $file_name . '"');
             }
    //header("Content-Disposition: attachment;filename={$file_name}");
    $buffer = 1024;
    $file_count = 0;
    //判断文件是否结束
    while (!feof($fp) && ($file_size-$file_count>0)) {
    $file_data = fread($fp, $buffer);
    $file_count += $buffer;
    echo $file_data;
    }
    fclose($fp); //关闭文件
    }
    /**
    * 删除文件
    * @param string $filename
    */
   public function delFile($fileid) {
    if (file_exists($filename)) unlink($filename);
    }
     
	/**todo
	*集体备课查询
	*/
   public function search(){
    
    $sublist=D('JxSubject')->order(array('sort'=>'asc'))->where(array('satus'=>1))->field('id,subject')->select();
   	/**查询字段条件拼组**/ 
    $map['status']=1;
    $search=I('keywords');
    $grade=I('post.grade');
    $subject=I('post.subject');
    if(!empty($search)){
      $map['keyword'] = array('like','%'.$search.'%');
    }else{
      unset($map['keyword']);
    }
   if('所有年级'==$grade||empty($grade)){
    unset($map['grade']);
   }else{
    $map['grade']=I('grade');
   }
   if('所有学科'==$subject||empty($subject)){
    unset($map['subject']);
   }else{
    $map['subject']=I('subject');
   }
  
  
   	//like模糊查询
   	$postsearch=D('JxShitiFile')->field('status,last_reply_time,s_key',true)->order('update_time desc')->where($map)->limit(20)->select();
    //dump($map);
    //dump($sublist);
    //dump($postsearch);
     $this->assign('list',$postsearch);
     $this->assign('subjectlist',$sublist);
     $this->display();
   }


}